package org.x.legalcasemod.service.Impl;

import com.mybatisflex.core.query.QueryWrapper;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.stereotype.Service;

import cn.idev.excel.FastExcel;
import cn.idev.excel.write.builder.ExcelWriterBuilder;
import cn.idev.excel.write.builder.ExcelWriterSheetBuilder;
import org.x.commonmod.GlobalEnumConverter;
import org.x.legalcasemod.entity.CaseMaterialEntity;
import org.x.legalcasemod.mapper.CaseManagementMapper;
import org.x.legalcasemod.mapper.CaseMaterialMapper;
import org.x.legalcasemod.service.ExcelService;

import java.io.IOException;
import java.net.URLEncoder;
import java.nio.charset.StandardCharsets;
import java.util.List;

@Service
public class ExcelServiceImpl implements ExcelService {

    private final CaseManagementMapper caseMapper;
    private final CaseMaterialMapper materialMapper;

    public ExcelServiceImpl(CaseManagementMapper caseMapper, CaseMaterialMapper materialMapper) {
        this.caseMapper = caseMapper;
        this.materialMapper = materialMapper;
    }

    public void exportCaseToBrowser(String caseNo, HttpServletResponse response) throws IOException {
        // 1. 查询数据等操作
        List<CaseMaterialEntity> materials = materialMapper.selectListByQuery(
                new QueryWrapper().eq("case_no", caseNo)
        );
        // 2. 设置响应头等操作
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        String encodedFileName = URLEncoder.encode("案件详情_" + caseNo + ".xlsx", StandardCharsets.UTF_8);
        response.setHeader("Content-Disposition", "attachment; filename=\"" + encodedFileName + "\"");

        // 3. 创建 ExcelWriterBuilder
        ExcelWriterBuilder writerBuilder = FastExcel.write(response.getOutputStream(), CaseMaterialEntity.class);
        try {
            // 4. 注册枚举转换器等操作
            writerBuilder.registerConverter(new GlobalEnumConverter());
            ExcelWriterSheetBuilder sheetBuilder = writerBuilder.sheet("案件材料");
            sheetBuilder.doWrite(materials);
        } finally {
            // 5. 手动关闭资源
            writerBuilder.autoCloseStream(true);
        }
    }
}